/*
 * Timer.cpp
 *
 * Created: 29/09/2012 09:15:42
 *  Author: Richard
 */ 

#include <Arduino.h>

#include "Timer.h"

void startTimerOne() {
	cli();
	TCCR1A = 0;  /* reset the control vectors */
	TCCR1B = 0;
	
	TCCR1A = _BV(COM1B1); /* enable OC1B PWM output */
	TCCR1B = _BV(CS12) | _BV(CS10) | _BV(WGM13); /* setup phase & frequency correct PWM mode, firing ICR1 at the bottom
													also CS12 & CS10 set prescaler to 1/1024 */
	ICR1  = 0xFFFF; /* ensure that the counter counts all the way to the top */
	TCNT1 = 0; // set counter to zero
	
	TIFR1 = OCF1A; /* clear timer1 compare interrupts */
	TIFR1 = OCF1B; 
	TIFR1 = TOV1; /* clear the overflow interrupt */
	
	TIMSK1 |= _BV(OCIE1A); // enable timer1 compare interrupt
	TIMSK1 |= _BV(TOIE1);  // enable timer1 overflow interrupt		
	sei(); //enable global interrupts
}

void setTimerOneDutyCycle ( long value ) {
	OCR1A = value;
}

void startTimerTwo() {
	cli();
	TCCR2A = 0;
	TCCR2B = 0;

	OCR2A = 0xFF; // TODO: the CTC register is set tp FF, so I could just use normal mode 
	
	TCCR2B |= (1 << WGM22); // turn on CTC mode
	TCCR2B |= (1 << CS20) | (1 << CS22); // enable 1024 prescaler
	TCNT2 = 0; // set counter to zero
	
	TIFR2 = OCF2A; // clear timer2 compare interrupt
	TIFR2 = OCF2B; //
	TIMSK2 |= (1 << OCIE2A); // enable timer2 compare interrupt and overflow interrupt
	sei(); //enable global interrupts
}	

void stopTimerOne() {
	cli();
	TIMSK1 = (0 << OCIE1A); //disable timer1 compare interrupt
	sei();
}